
import java.awt.Color;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.text.Document;
import org.json.JSONException;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author gyf98
 */
public class ISBN extends javax.swing.JFrame {

    String ISBN = "9787302466833";
    HttpTookit h;
    Connection c;

    /**
     * Creates new form ISBN
     */
    public ISBN() {
        initComponents();
        setLocationRelativeTo(null);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
//System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        System.out.println(df.format(new java.util.Date()));
//        System.out.println(Date.valueOf(new LocalDate()));
        try {
            c = getConnection();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ISBN.class.getName()).log(Level.SEVERE, null, ex);
        }

        Document dt = jTextField1.getDocument();
        dt.addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
//                System.out.println("----");
                String s = jTextField1.getText();
                Map<String, String> map = null;
                if (s.length() == 13) {
                    jTextArea1.append(">>>>>>>>>>\r\n");
                    try {
                        map = h.search(s);
                        String sql = "insert into books (name,author,press,price,uploadtime,typeid,type,total,leave_number,isbn,isbn10,images,small_image,medium_image,large_image,published_date)"
                                + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        PreparedStatement ps = c.prepareStatement(sql);
                        ps.setString(1, map.get("title"));
                        if (map.get("author") == null || map.get("author").equals("")) {
                            ps.setNull(2, Types.VARCHAR);
                        } else {
                            String author = map.get("author");
                            author = author.replace("[", "");
                            author = author.replace("]", "");
                            author = author.replace("\"", "");
                            ps.setString(2, author);
                        }
                        if (map.get("publisher") == null || map.get("publisher").equals("")) {
                            ps.setNull(3, Types.VARCHAR);
                        } else {
                            ps.setString(3, map.get("publisher"));
                        }
                        if (map.get("price") == null || map.get("price").equals("")) {
                            ps.setNull(4, Types.DOUBLE);
                        } else {
                            String price = map.get("price").replace("元", "");
                            ps.setDouble(4, Double.parseDouble(price));
                        }
                        long time = new java.util.Date().getTime();
//                        ps.setDate(5, new Date(time));
                        ps.setTimestamp(5, new Timestamp(time));
                        ps.setInt(6, 3);
                        ps.setString(7, "计算机与互联网");
                        ps.setInt(8, Integer.parseInt(jTextField2.getText()));
                        ps.setInt(9, Integer.parseInt(jTextField2.getText()));
                        ps.setString(10, map.get("isbn13"));
                        if (map.get("isbn10") == null || map.get("isbn10").equals("")) {
                            ps.setNull(11, Types.VARCHAR);
                        } else {
                            ps.setString(11, map.get("isbn10"));
                        }
                        if (map.get("images") == null || map.get("images").equals("")) {
                            ps.setNull(12, Types.VARCHAR);
                        } else {
                            ps.setString(12, map.get("images"));
                        }
                        if (map.get("small") == null || map.get("small").equals("")) {
                            ps.setNull(13, Types.VARCHAR);
                        } else {
                            ps.setString(13, map.get("small"));
                        }
                        if (map.get("medium") == null || map.get("medium").equals("")) {
                            ps.setNull(14, Types.VARCHAR);
                        } else {
                            ps.setString(14, map.get("medium"));
                        }
                        if (map.get("large") == null || map.get("large").equals("")) {
                            ps.setNull(15, Types.VARCHAR);
                        } else {
                            ps.setString(15, map.get("large"));
                        }
                        if (map.get("pubdate") == null || map.get("pubdate").equals("")) {
                            ps.setNull(16, java.sql.Types.TIME);
                        } else {
                            try{
                                time = df1.parse(map.get("pubdate")).getTime();
                            }catch(Exception ee){
                                ps.setNull(16, java.sql.Types.TIME);
                            }
                            ps.setDate(16, new Date(time));
                        }
                        ps.executeUpdate();
                        jLabel5.setText(map.get("title"));
                        jLabel8.setText(map.get("isbn13") + "  " + jTextField2.getText() + "本");
                        jLabel6.setText("录入成功");
                        jLabel6.setForeground(Color.green);
                    } catch (JSONException | SQLException | NumberFormatException ex) {
                        Logger.getLogger(ISBN.class.getName()).log(Level.SEVERE, null, ex);
                        jLabel8.setText(jTextField1.getText());
                        jLabel6.setText("录入失败");
                        jLabel6.setForeground(Color.red);
                    }
                    jTextArea1.append("<<<<<<<<<<\r\n");
                    jTextArea1.setCaretPosition(jTextArea1.getText().length());
                    clear();
                }
            }

            /**
             * 文本内容减少时出发这个方法
             */
            @Override
            public void removeUpdate(DocumentEvent e) {
//                System.out.println("removeUpdate");
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
//                System.out.println("changedUpdate");
            }
        });

        h = new HttpTookit(jTextArea1);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("书籍信息录入器");

        jTextField1.setFont(new java.awt.Font("宋体", 0, 24)); // NOI18N
        jTextField1.setText("9787302466833");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel1.setFont(new java.awt.Font("宋体", 0, 24)); // NOI18N
        jLabel1.setText("书籍信息录入器");

        jLabel2.setFont(new java.awt.Font("宋体", 0, 24)); // NOI18N
        jLabel2.setText("ISBN:");

        jLabel3.setFont(new java.awt.Font("宋体", 0, 18)); // NOI18N
        jLabel3.setText("书籍名称：");

        jLabel4.setFont(new java.awt.Font("宋体", 0, 36)); // NOI18N
        jLabel4.setText("状态：");

        jButton1.setText("复位");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("宋体", 0, 18)); // NOI18N

        jLabel6.setFont(new java.awt.Font("幼圆", 0, 36)); // NOI18N
        jLabel6.setText(" ");

        jTextField2.setFont(new java.awt.Font("宋体", 0, 24)); // NOI18N
        jTextField2.setText("1");

        jLabel7.setFont(new java.awt.Font("宋体", 0, 24)); // NOI18N
        jLabel7.setText("本");

        jLabel8.setFont(new java.awt.Font("幼圆", 0, 36)); // NOI18N

        jLabel9.setForeground(new java.awt.Color(0, 0, 255));
        jLabel9.setText("帮助");
        jLabel9.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jLabel9MousePressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(237, 237, 237)
                .addComponent(jLabel1)
                .addContainerGap(259, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel4)
                        .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3)
                                .addComponent(jLabel2))
                            .addGap(24, 24, 24)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jLabel7))
                                .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)))
                        .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(73, 73, 73)
                        .addComponent(jLabel9)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(33, 33, 33)
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9)))
                    .addComponent(jScrollPane1))
                .addGap(16, 16, 16))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
        System.out.println("+-+-+-+-");
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        h = new HttpTookit(jTextArea1);
//        jTextField1.setText("");
        jTextArea1.setText("");
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jLabel9MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MousePressed
        // TODO add your handling code here:
        JOptionPane.showMessageDialog(null,
                "数据库地址必须为localhost\r\n"
                        + "数据库名必须为bookinfo\r\n"
                        + "用户名密码必须为root", "帮助", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_jLabel9MousePressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ISBN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ISBN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ISBN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ISBN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ISBN().setVisible(true);
            }
        });
    }

    public void clear() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                jTextField1.setText("");
            }
        }).start();
    }

//    public void insert(){
    public static Connection getConnection() throws ClassNotFoundException {

        String url = "jdbc:mysql://localhost:3306/bookinfo";//我连的数据库是MySQL中的jdbc数据库
        String username = "root";
        String password = "root";//我的MySQL数据库的密码是空字符串
        String driverClass = "com.mysql.jdbc.Driver";
        Connection ct = null;
        Class.forName(driverClass);
        try {
            ct = DriverManager.getConnection(url, username, password);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ct;
//	}

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
